import React  from 'react';
import {message,Icon,Button,Input,Row,Col,Card,Anchor,Table,Dropdown,Menu,Modal,Form,DatePicker,Upload,Select} from 'antd';
import styles from '../style/PropertyDataDetailInfo.scss';
import moment from 'moment';
import api from 'container/api';
import {
  ASSET_LEVEL,
  IS_NOT,
  GUARANTEE,
  TRANSPORT_TYPE,
  RETURNED_MONEY_WAY,
  RETURNED_MONEY_SOURCE,
  REMARK_TYPE
} from 'constants/index';
const ButtonGroup = Button.Group;
const Option = Select.Option;
const { TextArea } = Input;


const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 17 },
};

//其他信息
class OtherInfo extends React.Component {

  constructor(props){
    super(props);
    let {id} = props;
    this.state ={
      id,
      dataSource:[],
      footerData:{},
      editModal:false,
      isDetail:false,
      detail:{files:[]},
      upload:{
        loading:false,
      },
      isSelectExecution:false,
    }
  }

  componentWillMount(){
    this.doFetch()
  }

  async doFetch(){
    let {id} = this.state;
    let result = await api('/assets/remark/list' ,{id});
    if(!result.success){
      message.error(result.message)
      return
    }
    let data = result.data;
    this.setState({
      dataSource:data.item_list,
      footerData:{
        total_money:data.total_money
      }
    })
  }

  handleMenuClick(record,e){
    switch (e.key){
      case 'edit':
        this.openFormModal(record.id);
        break;
      case 'delete':
        Modal.confirm({
          title: '提示',
          content: '您确认删除该记录？',
          onOk:this.deleteById.bind(this,record.id),
        })
        break;
    };
  }

  async deleteById (id){
    let result = await api('/assets/remark/delete',{id});
    if(!result.success){
      message.error(result.message);
      return;
    }
    message.success('操作成功' , 1, () => {
      this.doFetch()
    })
  }

  async openFormModal(id){
    let {detail,isSelectExecution} = this.state;
    if(!id){
      this.setState({editModal:true})
      return
    }
    let result = await api('/assets/remark/detail' ,{id});
    if(!result.success){
      message.error(result.message);
      return
    }
    result.data.files =  result.data.files.map((item,index) => {
      return {
           uid: Math.random().toString(36).slice(2),      
           name: item.name,
           status: 'done', 
           type:item.type,
           url:item.url,
        }
    })
    this.props.form.setFieldsValue({files:result.data.files})
    this.setState({
      editModal:true,
      detail:result.data,
      isSelectExecution:result.data.type == "EXECUTION" ? true :false,
    })
    
  }

  //弹出确定
  handleOk = () => {
    this.props.form.validateFields((err, values) => {
      if (err) return;
      this.save({...values})
    });

  }
  async save(values) {
    let {detail,isSelectExecution} = this.state;
    if (isSelectExecution) {
      values.fee_date = values.fee_date.format('YYYY-MM-DD');
    }
    values.asset_id = this.state.id;
    if(detail.id){
      values.id = detail.id;
    }
    let result = await api('/assets/remark/edit' ,values);
    if(!result.success){
      message.error(result.message);
      return
    }

    message.success('保存成功' , 1, () => {
      this.setState({editModal:false},() =>{
        this.doFetch()
      })
    })
  }
  //取消弹出
  handleCancel = () =>{
    this.setState({
      editModal:false,
      detail:{},
      isDetail:false
    })
    this.props.form.resetFields();
  }
  uuid(){
    return Math.random().toString(36).slice(2);
  }

  uploadProps = (params) =>{
      this.uploadFile(params);
    }

  async uploadFile(params){
    let {
        file,
        filename,
      } = params;
      let {detail} = this.state;

      let result = await api.upload('/file/upload?file_type=7',file);
      if(result){
        let uid = this.uuid();
        detail.files.push({
          name:file.name,
          url:result.data.url,
          type:result.data.type,
          uid:uid,
          status:'done'
        })
      }
      this.props.form.setFieldsValue({
        files:detail.files
      })
      this.setState({detail})


  }


  // uploadProps = () => {
  //   let _this = this;
  //   let {detail,isDetail} = this.state;
  //   return {
  //     customRequest:async ({ file, fileList }) => {
  //       let {defaultFileList=[]} = this.state;
  //       let result = await api.upload('/file/upload?file_type=7',file);
  //       if(result){
  //         let uid = this.uuid();
  //         detail.files.push({
  //           name:file.name,
  //           url:result.data.url,
  //           type:result.data.type,
  //           uid:uid,
  //           status:'done'
  //         })
  //       }
  //       this.props.form.setFieldsValue({
  //         files:detail.files
  //       })
  //       this.setState({detail})
  //     },
  //     onRemove:(file) => {
  //       return !isDetail
  //     }
  //   }
  // }

  


  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }

  onChange(value){
    if (value == "EXECUTION") {
      this.setState({
        isSelectExecution:true,
      })
    }else{
      this.setState({
        isSelectExecution:false,
      })
    }
  }



  render(){
    let {dataSource,detail,isDetail,isSelectExecution} = this.state;
    const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
    let modalProps ={};
    if(isDetail){
      modalProps.footer = null;
      modalProps.title = '备注详情'
    }
    return (
      <div>
        <Card 
          title="其他信息" 
          bordered={false} 
          bodyStyle={{backgroundColor:'#fff',padding:'0'}}
          extra={
            <a href='javascript:void 0;' className={styles.cardExtraA} onClick={this.openFormModal.bind(this,null)}>
              <Icon style={{ fontSize: 18}} type="plus-circle-o" />
            </a>
          }
        >
          <Table
            size='small' 
            columns={this.getColumns()} 
            dataSource={dataSource} 
            rowKey={(record,index) => index}
            pagination={false}
            footer={this.renderTableFooter}
          />
        </Card>
        <Modal
          title={`${detail.id?'编辑':'添加'}备注`}
          visible={this.state.editModal}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={400}
          wrapClassName={"modal-from"}
          maskClosable={false}
          {...modalProps}
        >
          <Form layout="horizontal" >
            
            <Form.Item
              label="备注类型"
              {...formItemLayout}
            >
              {getFieldDecorator('type', {
                rules: [{ required: true, message: '请选择备注类型' }],
                initialValue:detail.type
              })(
                <Select style={{width:'100%'}}
                  onChange={this.onChange.bind(this)} >
                  {Object.keys(REMARK_TYPE).map((key,index) => {
                    return (<Option key={index} value={key}>{REMARK_TYPE[key]}</Option>)
                  })}
                </Select>
              )}
            </Form.Item>
            {isSelectExecution ? 
              <Form.Item
                label="费用日期"
                {...formItemLayout}
              >
                {getFieldDecorator('fee_date', {
                  rules: [{ required: false, message: '请选择备注日期' }],
                  initialValue:detail.fee_date?moment(detail.fee_date):null
                })(
                  <DatePicker style={{width:"100%"}}  />
                )}
              </Form.Item>
              :
              null
            }
            {isSelectExecution ? 
              <Form.Item
                label="费用金额"
                {...formItemLayout}
              >
                {getFieldDecorator('fee_money', {
                  rules: [{ required: false, message: '请输入涉及金额' }],
                  initialValue:detail.fee_money
                })(
                  <Input  placeholder="请输入涉及金额" addonAfter="元" />
                )}
              </Form.Item>
              :
              null
            }
            <Form.Item
              label="备注描述"
              {...formItemLayout}

            >
              {getFieldDecorator('detail', {
                rules: [{ required: true, message: '请选择备注详情' }],
                initialValue:detail.detail
              })(
                <TextArea placeholder="请输入备注详情"  autosize={{ minRows: 2, maxRows: 6 }} />
              )}
            </Form.Item>
            <Form.Item
              label="备注文件"
              {...formItemLayout}
            >
              {getFieldDecorator('files', {
                rules: [{ required: true, message: '请上传备注附件' }],
                valuePropName: 'fileList',
                getValueFromEvent: this.normFile,
                initialValue:detail.files
              })(
                <Upload 
                  customRequest={this.uploadProps}
                  onRemove={(file) => {
                    return !isDetail
                  }}>
                  {isDetail?null
                    :<Button disabled={isDetail}>
                      <Icon type="upload" /> 点击上传
                    </Button>
                  }
                  
                </Upload>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
  getColumns(){
    let columns = [
      {
        title: '备注日期',
        dataIndex: 'date',
        key: 'date',
      }, 
      {
        title: '备注人',
        dataIndex: 'person',
        key: 'person',
      }, 
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        render:(text) => {
          return REMARK_TYPE[text];
        }
      }, 
      {
        title: '涉及金额',
        dataIndex: 'fee_money',
        key: 'fee_money',
      },
      {
        title: '备注',
        dataIndex: 'detail',
        key: 'detail',
      },
      {
        title: '操作',
        key: 'action',
        width:100,
        render: (text, record) => (
          <ButtonGroup>
            <Button onClick={() => {
              this.setState({isDetail:true} , () => {
                this.openFormModal(record.id)
              })
            }}>详情</Button>
            <Dropdown 
              placement="bottomRight"
              overlay={
                <Menu onClick={this.handleMenuClick.bind(this,record)}>
                  <Menu.Item key="edit">编辑信息</Menu.Item>
                  <Menu.Item key="delete">删除记录</Menu.Item>
                </Menu>
              }
            >
            <Button  icon="bars" />
            </Dropdown>
          </ButtonGroup>
        ),
      }]
    return columns;
  }
  renderTableFooter = () => {
    let {footerData} = this.state;
    return (
      <div>
        执行费用：{footerData.total_money}元
      </div>
    )
  }
}
export default Form.create()(OtherInfo);
